
package com.gang.music.core.shiro;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.gang.music.core.interfaces.ShiroService;
import com.gang.music.core.toolbox.kit.DateKit;
import com.gang.music.system.entity.User;
import com.gang.music.system.service.UserService;
import com.smallchill.core.toolbox.kit.DateTimeKit;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class ShiroServiceImpl implements ShiroService{
	
	@Autowired
	private UserService userService;
	
	@Override
	public User user(String loginName) {
		
		EntityWrapper<User> ew = new EntityWrapper<>();
		ew.eq("login_name", loginName);
		User user = userService.selectOne(ew);
		// 账号不存在
		if (null == user) {
			throw new UnknownAccountException();
		}
		if(true == user.getLock()) {
			if(DateKit.compareDate(new Date(), user.getUnlockTime())) {
				user.recovery();
				userService.updateById(user);
			}else
				throw new ExcessiveAttemptsException(DateTimeKit.formatDateTime(user.getUnlockTime()));
		}
		
		return user;
	}

	@Override
	public ShiroUser shiroUser(User user) {
		
		return new ShiroUser(user.getId(), user.getLoginName(), user.getName());
	}
	
	@Override
	public List<String> findRolesByUserId(Long userId) {
		
		return userService.findUserRoleCodes(userId);
	}

	@Override
	public List<String> findPermissionsByUserId(Long userId) {
		
		return userService.findPermssionsByUserId(userId);
	}

	@Override
	public SimpleAuthenticationInfo info(ShiroUser shiroUser, User user, String realmName) {
		Object credentials = user.getPassword();
		// 密码加盐处理SimpleAuthenticationInfo
		ByteSource credentialsSalt = ByteSource.Util.bytes(user.getSalt());
		return new SimpleAuthenticationInfo(shiroUser, credentials, credentialsSalt, realmName);
	}
}
